<?php

class m120229_031525_material_base_data_import extends CDbMigration {
	public function safeUp() {
		return $this->importMaterialBaseData();
	}

	public function safeDown() {
		echo "********* ************************************** ********\n";
		echo "********* Please Manually rollback Material Data ********\n";
		echo "********* ************************************** ********\n";
	}

	private function importMaterialBaseData() {
		$dataFile = $this
			->utf8_fopen(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'material_base_data.csv');
		$nullString = '** NULL **';
		echo "Assuming NULL category is 16..\n";
		$nullCategoryId = 16;
		$success = true;
		try {
			$currentMaterial = null;
			$data = fgetcsv($dataFile);//skip one line;
			echo 'Skipping data: ' . implode(',', $data) . "\n";
			$countMaterial = 0;
			while ($data = fgetcsv($dataFile)) {
				if ($currentMaterial === null || $currentMaterial->name != $data[2]) {
					if ($currentMaterial !== null) {
						echo "Added " . $countMaterial . " model(s) to "
							. iconv('UTF-8', 'GB2312', $currentMaterial->name) . "\n";
					}
					$currentMaterial = new Material();
					$currentMaterial->disableBehaviors();
					if ($data[1] != $nullString) {
						$currentMaterial->categoryId = $data[1] - 1;
					} else {
						$currentMaterial->categoryId = $nullCategoryId;
					}
					$currentMaterial->name = $data[2];
					$currentMaterial->save();
					$countMaterial = 0;
				}
				$model = $data[3] == $nullString ? '' : $data[3];
				$exists = MaterialModel::model()
					->exists('materialId=:materialId AND model=:model',
						array(
							':materialId' => $currentMaterial->id,
							':model' => $model
						));
				if (!$exists) {
					$materialModel = new MaterialModel();
					$materialModel->disableBehaviors();
					$materialModel->materialId = $currentMaterial->id;
					$materialModel->model = $model;
					$materialModel->code = $data[0];
					$materialModel->unit = $data[4] == $nullString ? '(无单位)' : $data[4];
					$materialModel->statePrice = (empty($data[5]) || $data[5] == $nullString) ? '0'
						: $data[5];
					$materialModel->referenceCode = $data[6] == $nullString ? '' : $data[6];
					$materialModel->save();
					$countMaterial++;
				}
				//$materialModel
			}
		} catch (Exception $e) {
			echo 'Error: ' . $e->getMessage();
			$success = false;
		}
		fclose($dataFile);
		return $success;
	}

	private function utf8_fopen($fileName, $mode = 'r') {
		/*
		$fc = mb_convert_encoding(trim(file_get_contents($fileName)),'gb2312', 'utf-8');
		$handle = fopen("php://memory", $mode);
		fwrite($handle, trim($fc));
		fseek($handle, 0);
		/*/
		$handle = fopen($fileName, $mode);
		//*/
		return $handle;
	}
}
